import classnames from 'classnames'
import { useHistory } from 'react-router'
import { Dialog, NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import { getSuggestion, handleHistory } from '@/store/actions/search'
import { RootAction, RootState } from '@/types/store'
import { removeHistory } from '@/utils/history'

const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()

  const [val, setVal] = useState('')

  // const timeId = useRef(-1)

  const { run } = useDebounceFn(
    (val: string) => {
      // 这里放不希望频繁触发的 有防抖效果的代码...
      // console.log('我要去发请求了..', val)
      dispatch(getSuggestion(val))
    },
    {
      wait: 500,
    }
  )

  const suggestion = useSelector((state: RootState) => state.search.suggestion)

  const search = (val: string) => {
    if (!val.trim()) return

    // 对搜索过的关键字val 存储到本地 仓库

    dispatch(handleHistory(val))

    // 拿着val 去跳转到 搜索结果页
    history.push('/search/result?keyword=' + val)
  }

  const historyList = useSelector((state: RootState) => state.search.history)

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span
            className="search-text"
            onClick={() => {
              search(val)
            }}
          >
            搜索
          </span>
        }
      >
        <SearchBar
          value={val}
          onChange={(val) => {
            // val 用户输入的关键字
            setVal(val)

            // console.log('我要去发请求了..', val)
            run(val)

            // 需求: 发请求应该是等用户输入完成  停下来 500ms  再去做.. 不希望在连续输入过程中 发请求
            // 应该添加防抖效果!! 本质就是关延时器, 再开延时器
            // clearTimeout(timeId.current)
            // timeId.current = window.setTimeout(() => {
            //   console.log('我要去发请求了..', val)
            // }, 500)
          }}
          placeholder="请输入关键字搜索"
        />
      </NavBar>

      {/* 搜索历史 */}
      <div
        className="history"
        style={{
          display: val ? 'none' : 'block',
        }}
      >
        <div className="history-header">
          <span>搜索历史</span>
          <span
            onClick={() => {
              Dialog.confirm({
                content: '确认删除历史记录么?',
              }).then((res) => {
                // console.log(res)
                if (res) {
                  // 清空历史记录(仓库+ 本地)
                  dispatch({
                    type: 'search/set_history',
                    payload: [],
                  } as RootAction)

                  removeHistory()
                }
              })
            }}
          >
            <Icon name="iconbtn_del" />
            清除全部
          </span>
        </div>

        <div className="history-list">
          {historyList.map((item, index) => {
            return (
              <span
                onClick={() => {
                  search(item)
                }}
                className="history-item"
                key={index}
              >
                <span className="text-overflow">{item}</span>
                <Icon name="iconbtn_essay_close" />
              </span>
            )
          })}
        </div>
      </div>

      {/* 搜索建议 */}
      <div className={classnames('search-result', val ? 'show' : '')}>
        {suggestion.map((item, index) => {
          return (
            item && (
              <div
                className="result-item"
                key={index}
                onClick={() => search(item)}
              >
                <Icon className="icon-search" name="iconbtn_search" />
                <div
                  className="result-value text-overflow"
                  dangerouslySetInnerHTML={{
                    __html: item.replace(
                      new RegExp(val, 'ig'),
                      (match) => `<span>${match}</span>`
                    ),
                  }}
                >
                  {/* <span>黑马</span>
              程序员 */}
                  {/* {item.replace(
                new RegExp(val, 'ig'),
                (match) => `<span>${match}</span>`
              )} */}
                </div>
              </div>
            )
          )
        })}
      </div>
    </div>
  )
}

export default SearchPage
